package cdu.sl.controller;

import cdu.sl.common.Result;
import cdu.sl.dto.SaveUserDTO;
import cdu.sl.dto.UserLoginDTO;
import cdu.sl.dto.UserSignupDTO;
import cdu.sl.entity.User;
import cdu.sl.entity.User;
import cdu.sl.mapper.UserRolesDao;
import cdu.sl.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    private final UserRolesDao userRolesDao;

    private final AuthenticationManager authenticationManager;

    /**
     * 处理AJAX登录请求 - 此方法仅供AJAX调用
     * Spring Security会处理/users/login的POST请求，此方法用于前端需要JSON响应的情况
     * @param userLoginDTO 登录表单数据
     * @return
     */
    @PostMapping("/api/login")
    public Result customLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户AJAX登录:{}", userLoginDTO);
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            userLoginDTO.getUsername(),
                            userLoginDTO.getPassword()
                    )
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return Result.success("登录成功");
        } catch (AuthenticationException e) {
            return Result.error("登录出错: " + e.getMessage());
        }
    }

    /**
     * 用户注册
     * @param userSignupDTO 注册表单实体
     */
    @PostMapping("/signup")
    public Result signup(@RequestBody UserSignupDTO userSignupDTO) {
        log.info("用户注册：{}", userSignupDTO);
        userService.signup(userSignupDTO);
        return Result.success();
    }


    /**
     * 新增用户
     * @param saveUserDTO 新增用户数据实体
     * @return 统一响应结果
     */
    @PostMapping
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result addUser(@RequestBody SaveUserDTO saveUserDTO) {
        log.info("新增用户:{}", saveUserDTO);
        userService.add(saveUserDTO);
        return Result.success();
    }


    /**
     * 修改用户
     * @param saveUserDTO 修改用户数据实体
     * @return 统一响应结果
     */
    @PreAuthorize("hasAuthority('USER_UPDATE')")
    @PutMapping
    public Result updateUser(@RequestBody SaveUserDTO saveUserDTO) {
        log.info("修改用户：{}", saveUserDTO);
        userService.update(saveUserDTO);
        return Result.success();
    }


    /**
     * 删除用户
     * @param id 用户id
     * @return 统一响应结果
     */
    @PreAuthorize("hasAuthority('USER_DELETE')")
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        log.info("删除用户,用户id：{}", id);
        userService.delete(id);
        // 删除用户的同时删除用户在user_roles中的关联关系
        userRolesDao.deleteByUserId(id);
        return Result.success();
    }

    /**
     * 获取所有用户信息
     * @return 所有用户信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/list")
    public Result list() {
        log.info("获取所有用户信息");
        List<User> Users = userService.findAll();
        return Result.success(Users);
    }

    /**
     * 按照id查询用户信息
     * @param id 用户id
     * @return 用户信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("获取用户信息：{}", id);
        User User = userService.getById(id);
        return Result.success(User);
    }




}
